﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using AutoMapper;
using DevWeb.Biztalk.DeploymentSettings.Data.CodeFirst;

using DevWeb.Biztalk.DeploymentSettings.WebUI.Models;
using Microsoft.Practices.Unity;

namespace DevWeb.Biztalk.DeploymentSettings.WebUI.Controllers
{
    public class IntegrationVersionSettingController : BaseController
    {
        //
        // GET: /ntegrationVersionSetting/
        

        public ActionResult Index(int id)
        {

            Data.CodeFirst.IntegrationVersion dbversion = Context.IntegrationVersions.Include("Integration").Include("IntegrationVersionParameters").SingleOrDefault(p => p.Id.Equals(id));



         


            var model = Mapper.Map<List<IntegrationVersionSettingsViewModel>>(dbversion.IntegrationVersionParameters);
            ViewBag.id = id;

            return View(model);
        }


        public ActionResult Edit(int id)
        {
            var settingtoedit =
                Context.IntegrationVersionParameters
                    .Include("IntegrationVersion")
                    .Include("IntegrationVersion.Integration")
                    .FirstOrDefault(p => p.Id.Equals(id));


            var model = Mapper.Map<IntegrationVersionSettingsViewModel>(settingtoedit);

            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(IntegrationVersionSettingsViewModel model)
        {
            if (ModelState.IsValid)
            {
                var setting = Context.IntegrationVersionParameters.SingleOrDefault(p => p.Id.Equals(model.Id));


                var settingtosave = Mapper.Map(model, setting);


                Context.SaveChanges();

                return RedirectToAction("index", new {id = setting.IntegrationVersionId});
            }
            return View(model);
        }

        public ActionResult Create(int id)
        {


            var version = from v in Context.IntegrationVersions
                where v.Id == id
                select v;

           var item= version.Include(p => p.Integration).SingleOrDefault();




           IntegrationVersionParameter setting = new IntegrationVersionParameter() { CreateDateTime = DateTime.Now };

            setting.IntegrationVersion = item;
            setting.IntegrationVersionId = item.Id;

            var model = Mapper.Map<IntegrationVersionSettingsViewModel>(setting);


            return View(model);
        }

        [HttpPost]
        public ActionResult Create(IntegrationVersionSettingsViewModel model)
        {
            if (ModelState.IsValid)
            {
               
                var settingtosave = new IntegrationVersionParameter() { CreateDateTime = DateTime.Now };
                Mapper.Map(model, settingtosave);
                Context.IntegrationVersionParameters.Add(settingtosave);
                Context.SaveChanges();

                return RedirectToAction("Index", new {id = model.IntegrationVersionID});
            }


            return View(model);
        }

        public ActionResult Delete(int id)
        {
            var settingtodelete =
                Context.IntegrationVersionParameters
                    .Include("IntegrationVersion")
                    .Include("IntegrationVersion.Integration")
                    .FirstOrDefault(p => p.Id.Equals(id));


           
            if (settingtodelete != null)
            {
                var model = Mapper.Map<IntegrationVersionSettingsViewModel>(settingtodelete);
                model.IntegrationVersionID = settingtodelete.IntegrationVersionId;
                model.IntegrationName = settingtodelete.IntegrationName;
                model.ProductId = settingtodelete.ProductId;
                model.Version = settingtodelete.Version;
                return View(model);
            }
            throw new ArgumentException("Setting PAramater not found!");
        }


        [HttpPost]
        public ActionResult Delete(IntegrationVersionSettingsViewModel model)
        {
            var settingtodelete = Context.IntegrationVersionParameters.FirstOrDefault(p => p.Id.Equals(model.Id));


            Context.IntegrationVersionParameters.Remove(settingtodelete);
            Context.SaveChanges();

            return RedirectToAction("Index", new {id = model.IntegrationVersionID});
        }


        public ActionResult ParametersValues(int id)
        {
            var setting =
                Context.IntegrationVersionParameters
                    .Include("IntegrationVersionParameterValues")
                    .FirstOrDefault(p => p.Id.Equals(id));




            if (setting == null)
            {
                throw new ArgumentException("Setting is unknown");
            }

            var targetenvs = Context.TargetEnvironments.ToList();

            List<ParameterValue> valuelist = new List<ParameterValue>();
            var currentsettings = setting.IntegrationVersionParameterValues.ToList();

            foreach (var item in currentsettings)
            {
                var parametervalue = new ParameterValue();
                parametervalue.Environment = item.TargetEnvironment.Name;
                parametervalue.Value = item.Value;
                valuelist.Add(parametervalue);
                targetenvs.Remove(item.TargetEnvironment);
            }

            foreach (var targetEnvironment in targetenvs)
            {
                var newparametervalue = new ParameterValue();
                newparametervalue.Environment = targetEnvironment.Name;
                newparametervalue.Value = string.Empty;
                valuelist.Add(newparametervalue);
            }

            ParametersValuesModel model = new ParametersValuesModel(setting.Id, setting.ParameterName, valuelist, setting.CreateDateTime, setting.DefaultValue);



            

            return View(model);
        }


        [HttpPost]
        [ValidateInput(false)] 
        public ActionResult ParametersValues(FormCollection collection)
        {


            var id = int.Parse(collection["Id"]);
            var defaultvalue = collection["DefaultValue"];
            var parameter =
                Context.IntegrationVersionParameters.Include("IntegrationVersionParameterValues").SingleOrDefault(p => p.Id.Equals(id));
            parameter.DefaultValue = defaultvalue;
            if (parameter == null)
                throw new ArgumentException("IntegrationVersionParameter is not found");

            foreach (var targetEnvironment in Context.TargetEnvironments)
            {
                string newvalue = collection[targetEnvironment.Name];
                var currentvalues =
                    parameter.IntegrationVersionParameterValues.SingleOrDefault(
                        p => p.TargetEnvironmentId.Equals(targetEnvironment.Id));
                if (currentvalues != null)
                {

                    currentvalues.Value = newvalue;
                    currentvalues.CreateDateTime = DateTime.Now;

                }
                else
                {
                    var value = new IntegrationVersionParameterValue() { CreateDateTime = DateTime.Now };
                    value.TargetEnvironment = targetEnvironment;
                    value.TargetEnvironmentId = targetEnvironment.Id;
                    value.IntegrationVersionParameter= parameter;
                    value.IntegrationVersionParameterId = parameter.Id;
                    value.Value = newvalue;
                    parameter.IntegrationVersionParameterValues.Add(value);
                }
            }
            Context.SaveChanges();

            return RedirectToAction("Index" , new {Id= parameter.IntegrationVersionId});
        }
    }
}